package com.jayanslow.lighting.server.clients;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.net.Socket;

import com.jayanslow.lighting.protocol.commands.Net.NetDevice;
import com.jayanslow.lighting.protocol.misc.Bytes;
import com.jayanslow.lighting.protocol.misc.CharacterEncoding;
import com.jayanslow.lighting.server.parser.Errors;

public class Client extends Thread {
	private Socket socket;
	private ClientManager cman;
	private PrintWriter out;
	
	private String ip;
	private String name = "unknown";
	private short id;
	private NetDevice type;
	private boolean connected = false;
	
	public Client(ClientManager cman, Socket socket) {
		super("LightingServerClient" + cman.getNextId());
		this.id = cman.getNextId();
		cman.moveNextId();
		this.socket = socket;
		this.cman = cman;
		this.ip = socket.getInetAddress().toString().replace("/", "");
	}
	
	public String getIp() { return ip; }
	public String getDeviceName() { return name; }
	public short getClientId() { return id; }
	public NetDevice getClientType() { return type; }
	public ClientManager getManager() { return cman; }
	public boolean isConnected() { return connected; }
	
	public void setDeviceName(String name) {
		if (name.equals("")) name = ClientManager.DEFAULT_NAME;
		this.name = name;
	}
	
	public void run() {
		try {
			out = new PrintWriter(socket.getOutputStream(), true);
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			String inputLine;
			
			inputLine = in.readLine();
//			out.println("Connected to server");
			while ((inputLine = in.readLine()) != null) {
				//TODO: Check for Disconnect code
	            if (inputLine.equalsIgnoreCase("disconnect")) break;
	            else {
	            	try {
	            		cman.addCommand(this,inputLine);
	            	} catch (IllegalStateException e) {
	            		BigInteger big = Bytes.toBigInteger(Errors.QUEUE.getArray());
	            		String s = CharacterEncoding.CHAR128.encode(big);
	            		println(s);
	            	}
	            }
			}
			System.out.println("CLIENT DISCONNECT " + socket.getInetAddress().toString());
			out.close();
			in.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		cman.removeClient(this);
	}
	
	public void println(String s) {
		if (!connected) return;
		if (socket == null || out == null) return;
		out.println(s);
	}
	
	public void connect(NetDevice type, String name) {
		this.type = type;
		this.name = name;
		connected = true;
	}
	public void disconnect() {
		connected = false;
	}
}